Directory Listing in PHP

Course- PHP Tutorial >

Lets create a php function to list all files and folder in the specified directory using PHP inbuilt function readdir(). readdir() function returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem. You can specify the dir path to list all files and folder in side it or you can use dot(.) to list the current directory.

PHP Function

<?php
function dirListing($path){
if ($handle = opendir($path)) {
 while (false !== ($entry = readdir($handle))) {
   if ($entry != "." && $entry != "..") {
       $dirList .= $entry."<br>"; 
   }
 }
}
return $dirList;
}
?>

 

Call in Action

<?php
   echo dirListing('.');
?>

 

Output

The above function will list all files and folder in the current directory.

You can also use is_dir() function to check files and folders. The following function will distinct the folder and files.

function dirListing($path){
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
  if ($entry != "." && $entry != "..") {
    if(is_dir($entry)){
      $dirList .= $entry." - DIR <br>"; 
    }else{
      $dirList .= $entry." - FILE <br>";
    } 
  }
}
}
return $dirList;
}

 

Call in Action

<?php
   echo dirListing('.');
?>

 

Output

The above function will list all files and folder in the current directory and show "- DIR" when it find folder and "- FILE" in case of files.